package cn.org.theo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class Util {

    /**
     * 防止SQL注入
     * @param str
     * @return
     */
    public static String SQL(String str){
        return str.replaceAll(".*([';]+|(--)+).*"," ");
    }
    public static String HumbToUnderline(String name) {
        for(char i = 'A';i <= 'Z';i++){
            name = name.replace(i + "", ("_" + i).toLowerCase());
        }
        return name;
    }

    public static String nowTime(){

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);

    }

    /**
     * 时间戳 + 随机数
     * @return 生成token密匙
     */
    public static String getToken(String username){
        return UUID.randomUUID().toString().replace("-", "") + username;
    }

    public static void addCookie(String name, String value, HttpServletResponse resp){
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(30*60);
        resp.addCookie(cookie);
    }

    public static String getCookie(String name, HttpServletRequest req){
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie);
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)){
                return cookie.getValue();
            }
        }
        return null;
    }
}
